<template>
	<view class="normal-login-container">
		<view class="logo-content align-center justify-center flex">
			<image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
			</image>
			<text class="title">菌子好球</text>
		</view>

		<!-- 登录方式切换 -->
		<view class="login-type-tabs">
			<view class="tab-item" :class="{ active: loginType === 'phone' }" @tap="switchLoginType('phone')">
				手机号登录
			</view>
			<view class="tab-item" :class="{ active: loginType === 'account' }" @tap="switchLoginType('account')">
				账号登录
			</view>
		</view>

		<view class="login-form-content">
			<!-- 账号密码登录 -->
			<block v-if="loginType === 'account'">
				<view class="input-item flex align-center">
					<view class="iconfont icon-user icon"></view>
					<input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
				</view>
				<view class="input-item flex align-center">
					<view class="iconfont icon-password icon"></view>
					<input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码"
						maxlength="20" />
				</view>
				<view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
					<view class="iconfont icon-code icon"></view>
					<input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
					<view class="login-code">
						<image :src="codeUrl" @click="getCode" class="login-code-img"></image>
					</view>
				</view>
			</block>

			<!-- 手机号快捷登录 -->
			<block v-else>
				<view class="wechat-login-tip">
					<text>请使用微信手机号快捷登录</text>
				</view>
			</block>

			<view class="action-btn">
				<button v-if="loginType === 'account'" @click="handleLogin"
					class="login-btn cu-btn block bg-blue lg round">
					账号登录
				</button>
				<button v-else class="login-btn cu-btn block bg-blue lg round wechat-btn" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber">
					微信手机号登录
				</button>
			</view>

			<!-- <view class="reg text-center">
				<text class="text-grey1">没有账号？</text>
				<text @click="handleUserRegister" class="text-blue">立即注册</text>
			</view> -->

			<view class="xieyi text-center">
				<text class="text-grey1">登录即代表同意</text>
				<text @click="handleUserAgreement('1871072147519057922')" class="text-blue">《用户协议》</text>
				<text @click="handlePrivacy('1871072246265556994')" class="text-blue">《隐私协议》</text>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		getCodeImg,
		loginByWechat
	} from '@/api/login'

	import {
		setToken,
	} from '@/utils/auth'
	import storage from '@/utils/storage'
	import constant from '@/utils/constant'

	export default {
		data() {
			return {
				codeUrl: "",
				captchaEnabled: true,
				// 用户注册开关
				register: false,
				globalConfig: getApp().globalData.config,
				loginType: 'phone', // 登录方式:account-账号登录,phone-手机号登录
				loginForm: {
					username: "admin",
					password: "admin123",
					code: "",
					uuid: '',
					platform: 'MINI_PROGRAM'
				},
			}
		},
		created() {
			console.log('globalConfig', this.globalConfig)
		},
		methods: {
			// 用户注册
			handleUserRegister() {
				this.$tab.redirectTo(`/pages/register`)
			},
			// 隐私协议
			handlePrivacy(id) {
				this.$tab.redirectTo('/pages/notice?id=' + id)
			},
			// 用户协议
			handleUserAgreement(id) {
				this.$tab.redirectTo('/pages/notice?id=' + id)
			},
			// 获取图形验证码
			getCode() {
				getCodeImg().then(res => {
					this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled
					if (this.captchaEnabled) {
						this.codeUrl = 'data:image/gif;base64,' + res.data.img
						this.loginForm.uuid = res.data.uuid
					}
				})
			},
			// 切换登录方式
			switchLoginType(type) {
				this.loginType = type
				if (type === 'account') {
					this.getCode()
				}
			},
			// 登录方法
			async handleLogin() {
				if (this.loginType === 'account') {
					if (this.loginForm.username === "") {
						this.$modal.msgError("请输入您的账号")
					} else if (this.loginForm.password === "") {
						this.$modal.msgError("请输入您的密码")
					} else if (this.loginForm.code === "" && this.captchaEnabled) {
						this.$modal.msgError("请输入验证码")
					} else {
						this.$modal.loading("登录中，请耐心等待...")
						this.pwdLogin()
					}
				} else {
					this.$modal.loading("登录中，请耐心等待...")
					this.wechatLogin()
				}
			},
			// 密码登录
			async pwdLogin() {
				this.$store.dispatch('Login', this.loginForm).then(() => {
					this.$modal.closeLoading()
					this.loginSuccess()
				}).catch(() => {
					if (this.captchaEnabled) {
						this.getCode()
					}
				})
			},
			// 获取手机号
			async getPhoneNumber(e) {
				console.log('手机号信息:', e)
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					try {
						this.$modal.loading("登录中，请耐心等待...")

						// 获取登录code
						const loginRes = await new Promise((resolve, reject) => {
							uni.login({
								provider: 'weixin',
								success: (res) => {
									if (res.code) {
										resolve(res)
									} else {
										reject(new Error('登录失败'))
									}
								},
								fail: reject
							})
						})

						// 调用后端登录接口
						const res = await loginByWechat({
							code: loginRes.code,
							encryptedData: e.detail.encryptedData,
							iv: e.detail.iv,
							platform: 'MINI_PROGRAM'
						})

						this.$modal.closeLoading()
						if (res.code === 200) {
							uni.setStorageSync('storage_data', {
								vuex_token: res.data.token,
								vuex_user_info: res.data.userInfo
							})
							setToken(res.data.token)
							console.log('getPhoneNumber', res.data)
							let newUser = res.data.user.newUser;
							if (newUser) {
								setTimeout(() => {
									uni.showToast({
										title: '您的密码是初始密码和手机号一致，请尽快修改',
										icon: 'none'
									})
								}, 3000)
							}
							this.loginSuccess()
						}
					} catch (error) {
						this.$modal.closeLoading()
						console.error('微信登录失败:', error)
						this.$modal.msgError(error.errMsg || '微信登录失败，请重试')
					}
				} else {
					this.$modal.msgError('您已取消手机号授权')
				}
			},
			// 登录成功后，处理函数
			loginSuccess(result) {
				// 设置用户信息
				this.$store.dispatch('GetInfo').then(res => {
					let nextUrl = storage.get(constant.nextUrl);
					console.log('nextUrl', nextUrl)
					if (nextUrl && nextUrl !== '/') {
						this.$tab.reLaunch(nextUrl)
					} else {
						this.$tab.reLaunch('/pages/index/index')
					}
				}).catch(() => {
					uni.switchTab({
						url: '/pages/index/index'
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #ffffff;
	}

	.normal-login-container {
		width: 100%;

		.logo-content {
			width: 100%;
			font-size: 21px;
			text-align: center;
			padding-top: 15%;

			image {
				border-radius: 4px;
			}

			.title {
				margin-left: 10px;
			}
		}

		.login-form-content {
			text-align: center;
			margin: 20px auto;
			margin-top: 15%;
			width: 80%;

			.input-item {
				margin: 20px auto;
				background-color: #f5f6f7;
				height: 45px;
				border-radius: 20px;

				.icon {
					font-size: 38rpx;
					margin-left: 10px;
					color: #999;
				}

				.input {
					width: 100%;
					font-size: 14px;
					line-height: 20px;
					text-align: left;
					padding-left: 15px;
				}

			}

			.login-btn {
				margin-top: 40px;
				height: 45px;
			}

			.reg {
				margin-top: 15px;
			}

			.xieyi {
				color: #333;
				margin-top: 20px;
			}

			.login-code {
				height: 38px;
				float: right;

				.login-code-img {
					height: 38px;
					position: absolute;
					margin-left: 10px;
					width: 200rpx;
				}
			}
		}
	}

	.login-type-tabs {
		display: flex;
		justify-content: center;
		margin: 40rpx 0;

		.tab-item {
			padding: 20rpx 40rpx;
			font-size: 32rpx;
			color: #666;
			position: relative;

			&.active {
				color: #ff6b35;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background: #ff6b35;
					border-radius: 2rpx;
				}
			}
		}
	}

	.wechat-login-tip {
		text-align: center;
		padding: 40rpx 0;
		color: #666;
		font-size: 28rpx;
	}

	.wechat-btn {
		background-color: #07c160 !important;

		&:active {
			background-color: #06ad56 !important;
		}
	}
</style>